<template>
    <div>
        <div class="container1">
            <div class="common-title-flex">
                <div class="common-title-div"></div>
                <div class="common-title-text">角色查询条件</div>
            </div>
            <el-form ref="searchObj" :inline="true" :model="searchObj" size="mini" label-width="80px" style="margin-bottom:-10px;margin-top:10px;">
                    <el-form-item label="角色名称">
                        <el-input v-model="searchObj.roleName" placeholder="请输入角色名称" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-select v-model="searchObj.status" placeholder="请选择状态" style="width:100%;">
                            <el-option
                            v-for="item in statusList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item style="margin-left:2rem;">
                        <el-button type="primary" icon="el-icon-search" @click="query">查询</el-button>
                        <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
                    </el-form-item>
            </el-form>
        </div>
        <div class="container" style="margin-top:1rem;">
            <div class="common-list-class">
                <div style="display:flex;">
                    <div class="common-title-div"></div>
                    <div class="common-title-text">角色查询列表</div>
                </div>
                <el-button type="primary" style="height:32px;" icon="el-icon-circle-plus-outline" @click="addPolice">添加</el-button>
            </div>
            <!-- 查询列表 -->
            <el-table :data="tableData" size="mini" :row-style="rowStyle" :header-cell-style="tableHeaderColor" style="width: 100%;margin-top:10px;margin-bottom:10px;" max-height="550" border>
                <el-table-column type="index" label="序号" width="50" align="center">
                </el-table-column>
                <el-table-column prop="roleName" label="角色名称" width="300"  show-overflow-tooltip align="center">
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100"  show-overflow-tooltip align="center">
                    <template slot-scope="scope">
                        {{statusObj[scope.row.status]}}
                    </template>
                </el-table-column>
                <el-table-column prop="menuPermission" label="菜单权限" show-overflow-tooltip align="center">
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="360" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="editClick(scope.row)">修改</el-button>
                        <el-button type="warning" size="mini" icon="el-icon-tickets" @click="detailsClick(scope.row)">详情</el-button>
                        <el-button type="primary" size="mini" icon="el-icon-circle-check" v-if="scope.row.status == '0' && scope.row.sysInit !== 1" @click="startClick(scope.row)">启用</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-circle-close" v-if="scope.row.status == '1' && scope.row.sysInit !== 1" @click="stopClick(scope.row)">停用</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" v-if="scope.row.sysInit !== 1" @click="deleteClick(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-row type="flex" justify="end">
                    <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                    </el-pagination>
            </el-row>
        </div>
        <!-- 新增警员 和修改警员-->
        <el-dialog :title="isEditTitle" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="newaddFlag" width="30%" :before-close="handleClose" center>
            <div slot="title" class="header-title">
                <div class="header-title-div"></div>
                <div class="header-title-text">{{isEditTitle}}</div>
            </div>
            <el-form ref="inputObj" :model="inputObj" label-width="100px" :rules="rules">
                    <el-form-item label="角色类型" prop="roleType">
                        <el-select v-model="inputObj.roleType" placeholder="请选择角色类型" @change="roleTypeChange" style="width:100%;">
                            <el-option
                            v-for="item in roleTypeList"
                            :key="item.id"
                            :label="item.typeName"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="inputObj.roleName" placeholder="请输入角色名称" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="角色编码" prop="roleCode">
                        <el-input v-model="inputObj.roleCode" placeholder="请输入角色编码" clearable ></el-input>
                    </el-form-item>
                    <el-form-item class="required-content-red" label="菜单权限">
                        <el-tree
                        ref="tree"
                        @check-change="handleCheckChange"
                        :data="permissionContentList"
                        show-checkbox
                        node-key="id"
                        :default-checked-keys="checkedTreeList"
                        :props="defaultProps">
                        </el-tree>
                    </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submit">提 交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </span>
        </el-dialog>
        <!-- 警员详情 -->
        <el-dialog title="角色详情" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="detailsFlag" width="40%" :before-close="detailsClose" center>
            <div slot="title" class="header-title">
                <div class="header-title-div"></div>
                <div class="header-title-text">角色详情</div>
            </div>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">角色名称</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.roleName}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">角色编码</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.roleCode}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" style="font-weight: bold;background: whitesmoke;border:1px solid #eeeeee;text-align: center;">权限内容</el-col>
                <el-col :span="15" style="background: whitesmoke;border:1px solid #eeeeee;text-align: center;">
                         <el-tree :data="permissionContentList1" :props="defaultProps1" :default-expand-all="false"></el-tree>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button type="danger" size="mini" @click="detailsClose">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import mixin from '@/mixin/mixin.js'; 
    export default {
        name: 'rolemanager',
        mixins: [mixin],
        data(){
            return {
                statusList:[{
                    value:'',
                    label:'全部'
                },{
                    value:'0',
                    label:'已停用'
                },{
                    value:'1',
                    label:'已启用'
                }],
                roleTypeList:[],
                statusObj:{
                    '1':'已启用',
                    '0':'已停用'
                },
                uploadHeader:{
                  token:'1244567788'  
                },
                uploadUrl:'https://jsonplaceholder.typicode.com/posts/',
                rules:{
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ],
                    roleType: [
                        { required: true, message: '请选择角色类型', trigger: 'blur' }
                    ],
                    roleCode: [
                        { required: true, message: '请输入角色编码', trigger: 'blur' }
                    ],
                },
                checkedTreeList:[],
                defaultProps: {
                    children: 'permissionList',
                    label: 'menuName'
                },
                defaultProps1:{
                    children: 'permissionList',
                    label: 'menuName'
                },
                permissionContentList1:[],
                permissionContentList:[],
                detailsObj:{
                    roleName:'',
                    roleCode:''
                },
                inputObj:{
                    roleName:'',
                    roleType:'',
                    roleCode:''
                },
                detailsFlag:false,
                isEditTitle:'',
                newaddFlag:false,
                pageSizes:[10, 15, 50, 100],
                pagesize:10,
                total:10,
                currentPage:1,
                tableData: [],
                searchObj:{
                    roleName:'',
                    status:''
                },
                currentId:'',
                selectTreeList:[],
                // 用于标识点击修改后是否修改树组件
                flag:false,
                // 如果没有修改树组件，直接selectMenuList请求后台，如果修改过flag为true
                selectMenuList:[]
            }
        },
        created(){
            this.query();
            this.initQX();
        },
        methods: {
            tableHeaderColor({row,column,rowIndex,columnIndex}){
                return 'background-color:#f5f5f5;color:#626262;'
            },
            rowStyle({ row, rowIndex}){
                let style1={};
                let style2={};
                if(rowIndex%2 == 0){
                    style1.background = '#ffffff';
                    return style1
                }else{
                    style2.background = '#f5f5f5';
                    return style2
                }
            },
            initQX(){
                this.showLoading();
                this.$axios({
                    method: 'get',
                    url: `/system/queryMenuByMenuId`,
                    headers:{
                        Authorization:this.requestToken
                    },
                }).then(res => {
                    this.hideLoading();
                    if(res.data.code == '20000'){
                        
                        console.log("data----->:",res.data.data);
                        let dataList = res.data.data;
                        dataList.forEach((item)=>{
                            item.parentId = null;
                            if(item.permissionList && item.permissionList.length){
                                item.permissionList.forEach((item1)=>{
                                    item1.id = item.id+"-"+item1.id;
                                    item1.menuName = item1.permissionName;
                                })
                            }
                        })
                        this.permissionContentList = dataList;
                        
                    }else{
                        this.$message({
                            type: 'error',
                            message: res.data.message
                        });
                    }
                }).catch(err => {
                    this.hideLoading();
                    this.$message({
                        type: 'error',
                        message: err.response.data.message
                    });
                })
            },
            initRoleTypeList(){
                this.showLoading();
                this.$axios({
                    method: 'get',
                    url: `/system/queryRoleTypeList`,
                    headers:{
                        Authorization:this.requestToken
                    },
                }).then(res => {
                    this.hideLoading();
                    console.log(res);
                    if(res.data.code == '20000'){
                        this.roleTypeList = res.data.data;
                    }else{
                        this.$message({
                            type: 'error',
                            message: res.data.message
                        });
                    }
                }).catch(err => {
                    this.hideLoading();
                    this.$message({
                        type: 'error',
                        message: err.response.data.message
                    });
                })
            },
            handleCheckChange(){
                this.flag = true;
                let res = this.$refs.tree.getCheckedNodes(false,true)
                let arr = []
                res.forEach((item) => {
                    arr.push({
                        id:item.id,
                        label:item.menuName,
                        parentId:item.parentId
                    })
                })
                this.selectTreeList = arr;
                // console.log("选择的节点为：",arr)

            },
            // 新建确认和修改确认
            submit(){
                console.log(this.selectTreeList);
                let self = this;
                this.$refs['inputObj'].validate((valid) => {
                    if (valid) {
                        let dataList = [];
                        let data1 = []
                        if(self.flag){
                            if(!self.selectTreeList || !self.selectTreeList.length){
                                self.$message({
                                type:'error',
                                message:'请选择权限内容！'
                                })
                                return;
                            }
                            self.selectTreeList.forEach((item)=>{
                                if(!item.parentId || !item.parentId.length){
                                    dataList.push({
                                        menuId:item.id,
                                        permissionList:[]
                                    })
                                }
                            })
                            data1 = JSON.parse(JSON.stringify(dataList));
                                self.selectTreeList.forEach((item1)=>{
                                    data1.forEach((item2)=>{
                                    if(item1.parentId == item2.menuId){
                                        item2.permissionList.push(item1.id.split("-")[1])
                                    }
                                })
                            })
                        }else{
                            data1 = self.selectMenuList;
                        }
                        let params = {
                                tbRoleDO:{
                                    roleCode:self.inputObj.roleCode,
                                    roleName:self.inputObj.roleName,
                                    typeId:self.inputObj.roleType,
                                },
                                menuList:data1
                        }
                        if(self.isEditTitle == '修改角色'){
                            params.tbRoleDO.id = self.currentId;
                        }
                        let url = '';
                        if(self.isEditTitle == '修改角色'){
                            url = '/system/editRole'
                        }else{
                            url = '/system/addRole'
                        }
                        self.showLoading();
                        self.$axios({
                            method: 'post',
                            url: url,
                            headers:{
                                Authorization:this.requestToken 
                            },
                            data: params
                        }).then(res => {
                            self.hideLoading();
                            if(res.data.code == '20000'){
                                self.$message({
                                    message:res.data.message,
                                    type:'success'
                                })
                                self.newaddFlag = false;
                                self.checkedTreeList = [];
                                self.selectMenuList = [];
                                self.$refs.tree.setCheckedNodes([]);
                                self.query();
                            }else{
                                self.checkedTreeList = [];
                                self.selectMenuList = [];
                                self.$message({
                                    message:res.data.message,
                                    type:'error'
                                })
                            }
                            
                        }).catch(err=>{
                            self.hideLoading();
                            self.$message({
                                message:err.response.data.message,
                                type:'error'
                            })
                        })
                    } else {
                        return false;
                    }
                });
            },
            roleTypeChange(value){
                this.$forceUpdate();
            },
            // 取消点击
            cancel(){
                this.newaddFlag = false;
                // 设置树不选中节点
                this.$refs.tree.setCheckedNodes([]);
                // 收缩树节点
                for(var i = 0;i < this.$refs.tree.store._getAllNodes().length;i++){
        　　　　　　　　this.$refs.tree.store._getAllNodes()[i].expanded=false;
        　　　　　}
                this.checkedTreeList = [];
                this.inputObj = {
                    roleName:'',
                    roleType:'',
                    roleCode:''
                }
                this.$refs["inputObj"].resetFields();
            },
            // 取消点击
            handleClose(){
                this.cancel();
            },
            // 点击分页当前页多少数据
            handleSizeChange(val){
                this.pagesize = val;
                this.query();
            },
            // 点击分页页数
            handleCurrentChange(val){
                this.currentPage = val;
                this.query();
            },
            // 查询
            query() {
                let params = {
                    roleName:this.searchObj.roleName,
                    status:this.searchObj.status,
                    pageNumber:this.currentPage,
                    pageSize:this.pagesize
                }
                this.showLoading();
                this.$axios({
                        method: 'post',
                        url: `/system/queryRole`,
                        headers:{
                            Authorization:this.requestToken 
                        },
                        data: params,
                        params: params
                    }).then(res => {
                        this.hideLoading();
                        console.log('res---->:',res);
                        if(res.data.code == '20000'){
                            this.tableData = res.data.data.list;
                            this.pagesize = res.data.data.pageSize;
                            this.page = res.data.data.pageNumber;
                            this.total = res.data.data.total;
                        }else{
                            this.$message({
                                message:res.data.message,
                                type:'error'
                            })
                        }
                    }).catch(err => {
                        this.hideLoading();
                        this.$message({
                            message:err.response.data.message,
                            type:'error'
                        })
                    })
            },
            //  重置
            reset(){
                this.searchObj={
                    roleName:'',
                    status:''
                }
                this.query();
            },
            // 删除
            deleteClick(row){
                let self = this;
                this.$confirm('请确认是否删除该角色?', '删除', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    }).then(() => {
                    self.deleteMethod(row.id);
                    
                    }).catch(() => {
                        console.log('取消删除！')        
                    });
            },
            deleteMethod(id){
                this.showLoading();
                this.$axios({
                        method: 'get',
                        url: `/system/deleteRole/${id}`,
                        headers:{
                            Authorization:this.requestToken 
                        }
                    }).then(res => {
                        this.hideLoading();
                        console.log('res---->:',res);
                        if(res.data.code == '20000'){
                            this.query();
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }else{
                            this.$message({
                                message:res.data.message,
                                type:'error'
                            })
                        }
                    }).catch(err => {
                        this.hideLoading();
                        this.$message({
                            message:err.response.data.message,
                            type:'error'
                        })
                    })
            },
            // 新增
            addPolice(){
                this.initRoleTypeList();
                this.isEditTitle = '新增角色';
                this.newaddFlag = true;
                this.flag = true;
            },
            stopClick(row){
                let self = this;
                this.$confirm('请确认是否停用该角色?', '停用', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                }).then(() => {
                self.startandstopMethod(row.id,'0');
                }).catch(() => {
                    console.log('取消停用！')        
                });
            },
            // 启用
            startClick(row){
                let self = this;
                this.$confirm('请确认是否启用该角色?', '启用', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                }).then(() => {
                self.startandstopMethod(row.id,'1');
                }).catch(() => {
                    console.log('取消启用！')        
                });
            },
            startandstopMethod(id,status){
                this.showLoading();
                this.$axios({
                        method: 'get',
                        url: `/system/enableOrDisableRole/${id}/${status}`,
                        headers:{
                            Authorization:this.requestToken 
                        }
                    }).then(res => {
                        this.hideLoading();
                        console.log('res---->:',res);
                        if(res.data.code == '20000'){
                            this.query();
                            this.$message({
                                type: 'success',
                                message: res.data.message
                            });
                        }else{
                            this.$message({
                                message:res.data.message,
                                type:'error'
                            })
                        }
                    }).catch(err => {
                        this.hideLoading();
                        this.$message({
                            message:err.response.data.message,
                            type:'error'
                        })
                    })
            },
            // 详情
            detailsClick(row){
                let params = {
                    id:row.id
                }
                this.showLoading();
                this.$axios({
                        method: 'get',
                        url: `/system/detailsRole`,
                        headers:{
                            Authorization:this.requestToken 
                        },
                        data: params,
                        params: params
                    }).then(res => {
                        this.hideLoading();
                        console.log('res---->:',res);
                        if(res.data.code == '20000'){
                            this.detailsFlag = true;
                            let dataList = res.data.data.menuList;
                            dataList.forEach((item)=>{
                                if(item.permissionList && item.permissionList.length){
                                    item.permissionList.forEach((item1)=>{
                                        item1.menuName = item1.permissionName
                                    })
                                }
                                
                            })
                            this.permissionContentList1 = dataList;
                            this.detailsObj.roleName = res.data.data.roleName;
                            this.detailsObj.roleCode = res.data.data.roleCode;
                        }else{
                            this.$message({
                                message:res.data.message,
                                type:'error'
                            })
                        }
                    }).catch(err => {
                        this.hideLoading();
                        this.$message({
                            message:err.response.data.message,
                            type:'error'
                        })
                    })
                
            },
            // 详情关闭
            detailsClose(){
                this.detailsFlag = false;
            },
            // 修改
            editClick(row){
                let self = this;
                self.selectMenuList = [];
                self.flag = false;
                self.currentId = row.id;
                this.initRoleTypeList();
                this.isEditTitle = '修改角色';
                let params = {
                    id:row.id
                }
                this.showLoading();
                this.$axios({
                        method: 'get',
                        url: `/system/detailsRole`,
                        headers:{
                            Authorization:this.requestToken 
                        },
                        data: params,
                        params: params
                    }).then(res => {
                        this.hideLoading();
                        console.log('res---->:',res);
                        if(res.data.code == '20000'){
                            this.newaddFlag = true;
                            let dataList = res.data.data.menuList;
                            let dataCopy = JSON.parse(JSON.stringify(dataList));
                            let selectMenuList = [];
                            dataCopy.forEach((item)=>{
                                selectMenuList.push({
                                    menuId:item.id,
                                    permissionList:item.permissionList.map(value=>value['id'])
                                })
                            })
                            self.selectMenuList = selectMenuList;
                            dataList.forEach((item)=>{
                                if(item.permissionList && item.permissionList.length){
                                    item.permissionList.forEach((item1)=>{
                                        item1.menuName = item1.permissionName
                                    })
                                }
                            })
                            console.log('dataList----',dataList);
                            // self.selectMenuList

                            dataList.forEach((item)=>{
                                item.permissionList.forEach((item1)=>{
                                    item1.id = item.id+"-"+item1.id
                                })
                            })
                            let list = [];
                            dataList.forEach((item)=>{
                                item.permissionList.forEach((item1)=>{
                                    list.push(item1.id)
                                })
                            })
                            this.checkedTreeList = list;
                            
                            // this.$refs.tree.setCheckedNodes(dataList)
                            this.inputObj.roleName = res.data.data.roleName;
                            this.inputObj.roleCode = res.data.data.roleCode;
                            this.inputObj.roleType = res.data.data.typeId;
                            
                        }else{
                            this.$message({
                                message:res.data.message,
                                type:'error'
                            })
                        }
                    }).catch(err => {
                        this.hideLoading();
                        this.$message({
                            message:err,
                            type:'error'
                        })
                    })
                    
            }
        }
    }
</script>
<style scoped>  
  .common-title-flex{
      display:flex;
  }
  .common-title-div{
      width:3px;
      height:16px;
      background-color:#368af7;
      margin-top:2px;
  }
  .common-title-text{
      margin-left:4px;
      font-size: 14px;
  }
  .common-list-class{
      display:flex;
      justify-content:space-between;
      margin-top:-10px;
  }
</style>>